package com.ph.interceptor;

import java.util.List;
import java.util.Map;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.ph.irp.base.usermanage.service.UserManageService;
import com.ph.irp.login.action.LoginAction;

public class AuthorizationInterceptor extends AbstractInterceptor {
	private UserManageService userManageService;
	private static final long serialVersionUID = 4949812834762901805L;
	private static final String NO_PERMIT="noPermit";
	private static final int adminID=15;


	public void setUserManageService(UserManageService userManageService) {
		this.userManageService = userManageService;
	}

	@Override
	public String intercept(ActionInvocation actionExecute) throws Exception {
		boolean flag = false;// 如果有权限访问设置为true；
		Object action = actionExecute.getAction();

		if (action instanceof LoginAction) {
			// 如果用户想登录，则使之通过
			return actionExecute.invoke();
		}
		Map session = actionExecute.getInvocationContext().getSession();

		if (session.isEmpty()) {
			return Action.LOGIN;
		} else {
			int userID = (Integer) session.get("userId");
			if (userID == adminID) {
				return actionExecute.invoke();
			}

			try {
				// 获取当前用户所拥有的角色
				List<Integer> roleIDs = userManageService
						.getUserRoleByUserId(String.valueOf(userID));
				if (roleIDs == null || roleIDs.size() == 0) {	// 没有任何角色		
					return NO_PERMIT;
				}
		
				for (int roleID : roleIDs) {
					List<Integer> functionTypeIDs = userManageService
							.getFunctionByRoleID(String.valueOf(roleID));

					for (int functionTypeID : functionTypeIDs) {
						//select operation
						if(actionExecute.getProxy().getActionName().contains("select")){
							flag = true;
							break;
						}
						String actionName = actionExecute.getProxy()
								.getAction().toString();
						String functionTypeName = userManageService
								.getFunctionTypeNameByFunctionTypeID(String
										.valueOf(functionTypeID));

						if (functionTypeName != null
								&& !functionTypeName.equals("")) {
							if (actionName
									.contains(userManageService
											.getFunctionTypeDescByFunctionTypeName(functionTypeName))) {
								flag = true;
								break;
							}
						}
					}
				}
			} catch (Throwable e) {
				e.printStackTrace();
			}
		}

		if (flag) {
			return actionExecute.invoke();
		} else {
			return NO_PERMIT;
		}
	}
}
